#pragma once

#include <cstdlib>
#include <cstring>

#include <iostream>
#include <string>
#include <functional>
#include <memory>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"

using namespace std;

//获取数据的方式与发送数据的方式由外部处理读写任务,服务器不需要关心
using io_service_t=function<void(socket_sptr,InetAddr)>;


// 多线程传递的参数
class ThreadData
{
public:
    ThreadData(socket_sptr fd, InetAddr client, TcpServer *s)
        : sockfd(fd), clientaddr(client), self(s)
    {

    }

public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port,io_service_t service)
        : _localaddr("0", port) // InetAddr类需要将构造函数重载
        , _listensock(new TcpSocket())
        , _isrunning(false)
        ,_service(service)
    {
        // 初始化服务器(创建套接字 --> 绑定 --->监听 )
        _listensock->BuildListenSocket(_localaddr);
    }

    /*
    void Service(socket_sptr sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link, info %s:%d, sockfd : %d", client.IP().c_str(), client.Port(), sockfd);

        string clientaddr = "[" + client.IP() + ":" + to_string(client.Port()) + "]# ";
        while (true)
        {
            char inbuffer[1024];
            ssize_t n = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
            }
            else if (n == 0)
            {
                // 客户端退出&&客户端关闭连接
                LOG(DEBUG, "%s quit", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error", clientaddr.c_str());
                break;
            }
        }
        ::close(sockfd);
    }
    */

    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 4.服务端获取客户端的连接请求
            InetAddr peeraddr;//InetAddr需要重载构造函数

            socket_sptr sock=_listensock->Accepter(&peeraddr);
            if(sock==nullptr)
            {
                continue;
            }

            ThreadData *td = new ThreadData(sock, peeraddr, this);
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerSock, td);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
    }

private:
    InetAddr _localaddr;            // IP地址与端口号port
    unique_ptr<Socket> _listensock; // 基类的指针
    bool _isrunning;
    io_service_t _service;
};